package com.sinodata.bsm.cicp.finder.sco;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.util.CommandReader;

/**
 * 
 * <p>
 * Description:  ScoSwap发现程序。
 * 程序返回：交换分区大小
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-12-26 AM 10:23:24   liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class ScoSwap extends ScoFinder {

    private static final Logger logger = Logger.getLogger(ScoSwap.class);
    private static final int M = 1024 * 1024;
    //private static final int blockSize = 512;
    private static final String SHELL = "/etc/swap -l  ";

    /*
    swap –l命令输出可能有多行，注意将值累加。
     1 block = 512 bytes
    # /etc/swap -l
    path            dev     swaplo blocks   free
    /dev/swap       1,41         0 585728 585728

    path            dev     swaplo  blocks  free
    /dev/swap       1,41         0   30000 25784
    /swap          76,1          0   15000 25784
    */

    @SuppressWarnings("unchecked")
    @Override
    public List<String[]> find(String ip, Map params) {
        List<String[]> list = new ArrayList<String[]>();
        String[] swapInfo = null;
        BufferedReader reader = null;
        String strLine = null;
        String ptnStr = "\\S*\\s+\\S+\\s+\\d+\\s+(\\d+)\\s+(\\d+).*";
        try {
            reader = CommandReader.getReader(ip, SHELL, 0, 0);
            long swapSize = 0L;
            while ((strLine = reader.readLine()) != null) {
                Pattern pattern = Pattern.compile(ptnStr);
                Matcher matcher = pattern.matcher(strLine);
                if (matcher.find()) {
                    swapSize += Long.parseLong(matcher.group(1));
                }
            }
            swapInfo = new String[4];
            list.add(swapInfo);
            swapInfo[0] = "swap";
            swapInfo[1] = "swap";
            swapInfo[2] = getHostName(ip) + " swap";
            swapInfo[3] = swapSize / M + ""; //交换分区大小
            return list;
        } catch (Exception e) {
            logger.error("failed to find scoswap", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("failed to close reader", e);
                }
            }
        }
        return null;
    }

}
